package com.sxt.controller;

import com.sxt.common.ActiveUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("login")
@Controller
public class LoginController {

//    跳转到登陆页面
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }
   // 做登陆

    @RequestMapping("doLogin")
    @ResponseBody
    public Map<String,Object> doLogin(String username, String password, HttpServletRequest request){
        Map<String,Object> map=new HashMap<>();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
            request.getSession().setAttribute("user",activeUser.getUser());
            map.put("code",200);
            map.put("msg","登陆成功");
            return map;
        }catch (AuthenticationException e){
            map.put("code",-1);
            map.put("msg","用户名或密码不正确");
            return map;
        }
    }
}
